// modules/goodModules/pages/commentList/index.js
import {findPageComment,checkIsBuy} from '@/api/comment.js'
import { msgTip } from '@/utils/MsgTipApi'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageIndex:1,
    pageSize:25,
    goodId:'',
    commentList:[],
    total:0,
    isAll:false
  },

  /**
   * 分页查询评论
   * @param {*} params 
   */
  async findCommentPage(params){
    if(!params){
      params = {pageIndex:1,pageSize:25,goodId:this.data.goodId}
    }
    let res = await findPageComment(params)
    this.setData({
      commentList:[...this.data.commentList,...res.records],
      total:res.total
    })
    this.setData({
      isAll:this.data.commentList.length >= this.data.total
    })
  },
  async pubComment(){
    let res = await checkIsBuy(this.data.goodId)
    if(res == true){
      wx.navigateTo({
        url: `/modules/commentModules/pages/commentPub/index?goodId=${this.data.goodId}`,
      })
    }else{
      msgTip({title:'未购买此商品，无法评论'})
    }
  },
  getPubComment(event){
   let {content} = event.detail;
   let {index} = event.detail;
   console.log(event);
   let sub = this.data.commentList[index].subComments || []
   sub.unshift(content)
   this.setData({
    [`commentList[${index}].subComments`]:sub
   })
  },
  // 移除评论
  toRemoveComment(event){
    let {index} = event.currentTarget.dataset;
    this.data.commentList.splice(index,1)
    this.setData({commentList:this.data.commentList})
    msgTip({title:"屏蔽成功"})
  },

  clearData(){
    this.setData({
      pageIndex:1,
      pageSize:25,
      commentList:[],
    }
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      goodId:options.goodId
    })
    let params = {
      pageIndex:this.data.pageIndex,
      pageSize:this.data.pageSize,
      goodId:options.goodId}
    this.findCommentPage(params)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.clearData()
    this.findCommentPage()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.isAll){
      return
    }
    this.data.pageIndex++;
    let params = { 
      pageIndex:this.data.pageIndex,
      pageSize:25,
      goodId:this.data.goodId
    }
    this.findCommentPage(params)

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})